from libs.extensions.basebk import *
from libs.bkend.ldapResources.ldaputils import *
from libs.bkend.ldapResources.user import *
from django.contrib.auth.models import User
import ldap
import re

def save_Udetail(inst):
    l = ldapConnect()
    if l:
        ps = False
        try:
            ps = l.search_s("", ldap.SCOPE_SUBTREE, "uid="+inst.user.username)
        except:
            pass
        if inst.user_type == "developers":
            ssh = True
        else:
            ssh = False
        if ps:
            if inst.raw_passwd:
                cryptpw = cryptPassword(inst.raw_passwd)
                l.modify_s(ps[0][0], [(ldap.MOD_REPLACE, "userPassword", "{crypt}" + cryptpw)])
            l.modify_s(ps[0][0], [(ldap.MOD_REPLACE, "cn", inst.user.first_name + " " + inst.user.last_name)])  #FIXIT
            l.modify_s(ps[0][0], [(ldap.MOD_REPLACE, "sn", inst.user.last_name)])
            l.modify_s(ps[0][0], [(ldap.MOD_REPLACE, "givenName", inst.user.first_name)])
            TMLIST = ps[0][1]['objectClass']
            if not TMLIST.count('apacheConfig'):
                TMLIST.append("apacheConfig")

                docroot = u"/home/%s/public_html"%inst.user.username
                l.modify_s(ps[0][0],[(ldap.MOD_REPLACE, "objectClass", TMLIST),
                                         (ldap.MOD_ADD, "apacheServerName", str(inst.www)),
                                         (ldap.MOD_ADD, "apacheDocumentRoot", str(docroot))])
            else:
                l.modify_s(ps[0][0], [(ldap.MOD_REPLACE, "apacheServerName", str(inst.www))])
            l.modify_s(ps[0][0], [(ldap.MOD_REPLACE, "emailContact", inst.user.email)])
            #l.modify_s(ps[0][0], [(ldap.MOD_REPLACE, "domain", re.search("@(?P<dom>.*)", inst.user.email).group(1))])
            #l.modify_s(ps[0][0], [(ldap.MOD_REPLACE, "maildir", "%s/%s/"%(re.search("@(?P<dom>.*)", inst.user.email).group(1), re.search("(?PWeebotee.*)@", inst.user.email).group(1)))])
            if ssh:
                ssh = "/bin/bash"
            else:
                ssh = "/dev/null"
            l.modify_s(ps[0][0], [(ldap.MOD_REPLACE, "loginShell", ssh)])
            return
        else:
            p = userManager(inst.user.username, inst.user_type, inst.website, inst.user.email, inst.user.username, inst.raw_passwd, ssh)
            p.save()
    else:
        print "merda"
    return true
        
def drop_User(inst):
    l = ldapConnect()
    if not l:
        return True
    try:
        u = l.search_s("", ldap.SCOPE_SUBTREE, "(&(objectClass=inetOrgPerson)(uid=%s))"%inst.username)
    except Exception, e:
        u = False
    if u:
        l.delete_s(u[0][0])
        l.delete_s("cn="+inst.username+",ou=group,o="dbsolution sas",dc=localnet,dc=org")
        if self.types == 'commerciali':
            l.modify_s("cn=commerciali,ou=group,o="dbsolution sas",dc=localnet,dc=org", [(ldap.MOD_DELETE, 'memberUid', str(inst.username))])
    
    return True

class LdapAuthBackend:
    """Authenticate using LDAP
    """
    def authenticate(self, username=None, password=None):
        l = ldapConnect()
        if not l:
            return
        try:
            l.simple_bind_s("uid="+username+",ou=developers,ou=people,o="dbsolution sas",dc=localnet,dc=org", password)
            valid = True
        except ldap.LDAPError, e:
            try:
                l.simple_bind_s("uid="+username+",ou=clients,o="dbsolution sas",dc=localnet,dc=org", password)
                valid = True
            except ldap.LDAPError, e:
                try:
                    l.simple_bind_s("uid="+username+",ou=commerciali,ou=people,o="dbsolution sas",dc=localnet,dc=org", password)
                    valid = True
                except ldap.LDAPError, e:
                    valid = False

        if valid:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                # Create a new user. Note that we can set password to anything
                # as it won't be checked, the password from settings.py will.
                U = l.search_s("",
                                ldap.SCOPE_SUBTREE,
                                "uid="+username)
                user = User(username=username,password="****")
                user.set_password(password)
                user.is_active = True 
            return user
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
